<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="4">
        <el-switch
          style="display: block"
          v-model="draggable"
          active-color="#13ce66"
          active-text="开启拖拽"
          inactive-text="关闭拖拽"
          @change="changeDraggable">
        </el-switch>
      </el-col>
      <el-col :span="3">
        <el-button v-if="draggable" @click="batchSave" size="mini">批量保存</el-button>
      </el-col>
      <el-col :span="3">
        <el-button type="danger" @click="batchDelete" size="mini">批量删除</el-button>
      </el-col>
    </el-row>
    <br>

    <el-tree
      ref="tree"
      :data="menus"
      :props="defaultProps"
      :expand-on-click-node="false"
      node-key="catId"
      :default-expanded-keys="expandedKey"
      show-checkbox
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      @node-collapse="handleCollapse"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level < 3"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button type="text" size="mini" @click="() => edit(data)">
            Edit
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        // 对话框的类型
        dialogType: "", //add,edit
        dialogTitle: "",
        menus: [],
        // 默认要展开的菜单
        expandedKey: [],
        defaultProps: {
          children: "children",
          label: "name",
        },

        // 添加对话框
        dialogFormVisible: false,
        category: {
          catId: null,
          name: "",
          parentCid: 0,
          catLevel: 0,
          showStatus: 1,
          sort: 0,
          icon: "",
          productUnit: "",
        },

        //是否开启拖拽功能
        draggable: false,

        //拖拽功能要修改的node
        updateNodes: [],
      };
    },
    methods: {
      //点击拖拽按钮处理函数
      changeDraggable() {
        if (!this.draggable) {
          console.log(this.draggable)
          this.getMenus();
        }
      },
      //批量删除
      batchDelete() {
        let catIds = [];
        let checkedNodes = this.$refs["tree"].getCheckedNodes();
        for (const checkedNode of checkedNodes) {
          catIds.push(checkedNode.catId);
        }
        this.$confirm(
          `确定对[${catIds}]进行[${catIds ? "删除" : "批量删除"}]操作?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false),
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.getMenus();
              this.expandedKey.push(node.parent.data.catId);
              this.$message({
                message: "操作成功",
                type: "success",
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }).catch(() => {
        });
      },
      //判断节点是否可以被拖拽
      allowDrop(draggingNode, dropNode, type) {
        if (type === "inner") {
          return this.countNodeLevel(draggingNode.data) + dropNode.level < 4;
        } else {
          return (
            this.countNodeLevel(draggingNode.data) + dropNode.parent.level < 4
          );
        }
      },
      //计算节点层数
      countNodeLevel(category) {
        let deep = 1;
        //找出所有子节点，求出最大深度
        for (const node of category.children) {
          deep = Math.max(deep, this.countNodeLevel(node) + 1);
        }
        return deep;
      },
      //拖拽成功后的处理函数
      handleDrop(draggingNode, dropNode, dropType, ev) {
        console.log("tree drop: ", draggingNode, dropNode, dropType);
        //1. 当前节点最新的父节点id
        let pCid = 0;
        //当前节点的拖拽后的列表
        let siblings = null;
        if (dropType === "inner") {
          pCid = dropNode.data.catId;
          siblings = dropNode.childNodes;
        } else {
          pCid =
            dropNode.parent.data.catId == undefined
              ? 0
              : dropNode.parent.data.catId;
          siblings = dropNode.parent.childNodes;
        }
        this.expandedKey.push(pCid);

        //2. 当前拖拽节点的最新顺序
        for (let i = 0; i < siblings.length; i++) {
          if (siblings[i].data.catId == draggingNode.data.catId) {
            //如果当前遍历的是拖拽的节点
            let catLevel = draggingNode.level;
            if (siblings[i].data.catLevel != siblings[i].level) {
              //当前节点层级发生了改变
              catLevel = siblings[i].level;
              //修改所有子节点的层级
              this.updateChildNodeLevel(siblings[i]);
            }
            this.updateNodes.push({
              catId: siblings[i].data.catId,
              sort: i,
              parentCid: pCid,
              catLevel: catLevel,
            });
          } else {
            this.updateNodes.push({catId: siblings[i].data.catId, sort: i});
          }
        }
        console.log(this.updateNodes);
      },
      //拖拽后批量保存
      batchSave() {
        this.$http({
          url: this.$http.adornUrl("/product/category/update/sort"),
          method: "post",
          data: this.$http.adornData(this.updateNodes, false),
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: "菜单顺序修改成功",
              type: "success",
            });
            this.getMenus();
            this.updateNodes = [];
          }
        });
      },
      //节点被关闭时处理方法
      handleCollapse(category) {
        let i = -1;
        for (let j = 0; j < this.expandedKey.length; j++) {
          if (this.expandedKey[i] === category.catId) {
            i = j;
            break;
          }
        }
        if (i !== -1) {
          this.expandedKey.splice(i, 1);
        }
      },
      //修改所有子节点的层级
      updateChildNodeLevel(node) {
        if (node.childNodes != null && node.childNodes.length > 0) {
          for (const n of node.childNodes) {
            this.updateNodes.push({catId: n.data.catId, catLevel: n.level});
            this.updateChildNodeLevel(n);
          }
        }
      },
      handleNodeClick(data) {
        console.log(data);
      },
      getMenus() {
        this.$http({
          url: this.$http.adornUrl("/product/category/list/tree"),
          method: "get",
        }).then(({data}) => {
          console.log(data.data);
          this.menus = data.data;
        });
      },
      submitData() {
        this.dialogType === "add" ? this.addCategory() : this.editCategory();
      },
      //打开编辑框
      edit(data) {
        this.dialogType = "edit";
        this.dialogTitle = "修改分类";
        this.$http({
          url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
          method: "get",
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log(data);
            this.category = data.category;
          }
          this.dialogFormVisible = true;
        });
      },
      //发送请求编辑category
      editCategory() {
        var {catId, name, icon, productUnit} = this.category;
        this.$http({
          url: this.$http.adornUrl("/product/category/update"),
          method: "post",
          data: this.$http.adornData({catId, name, icon, productUnit}, false),
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.getMenus();
            this.dialogFormVisible = false;
            this.expandedKey.push(this.category.catId);
            this.$message({
              message: "修改成功",
              type: "success",
            });
          }
        });
      },
      //添加category
      addCategory() {
        console.log(this.category);
        this.$http({
          url: this.$http.adornUrl("/product/category/save"),
          method: "post",
          data: this.$http.adornData(this.category, false),
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.getMenus();
            this.dialogFormVisible = false;

            this.$message({
              message: "操作成功",
              type: "success",
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      },
      //打开添加框
      append(data) {
        console.log(data);
        this.category.parentCid = data.catId;
        this.category.catLevel = parseInt(data.catLevel) + 1;
        this.dialogFormVisible = true;
        this.dialogType = "add";
        this.dialogTitle = "添加分类";
        this.expandedKey.push(data.catId);
      },
      // 删除
      remove(node, data) {
        // var ids = id
        //   ? [id]
        //   : this.dataListSelections.map((item) => {
        //       return item.roleId;
        //     });
        var ids = [data.catId];
        this.$confirm(
          `确定对[${data.name}]进行[${ids ? "删除" : "批量删除"}]操作?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            this.$http({
              url: this.$http.adornUrl("/product/category/delete"),
              method: "post",
              data: this.$http.adornData(ids, false),
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.getMenus();
                this.expandedKey.push(node.parent.data.catId);
                this.$message({
                  message: "操作成功",
                  type: "success",
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          })
          .catch(() => {
          });
      },
    },
    created() {
      this.getMenus();
    },
  };
</script>

<style>
</style>
